package com.awenhui.demo.task;

import com.awenhui.demo.config.properties.AppProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 创建外部配置文件
 *
 * @author yuxf
 * @version 1.0
 * @date 2021/6/29 14:43
 */
@Component
@Slf4j
public class AppStartRunner implements ApplicationRunner {
    @Autowired
    private AppProperty property;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("是否创建外部的配置文件："+property.isCreateOutConf());
        if (property.isCreateOutConf()) {
            // 处理生成外置配置文件
            if (property.isCreateOutConf()) {
                // 检测外置配置文件路径
                File file = new File("./config");
                if (!file.exists() || !file.isDirectory()) {
                    boolean result = file.mkdirs();
                    if (result) {
                        log.debug("------------StartConfig------------>createOutConfig:{}", "创建外置配置文件路径成功");
                    } else {
                        throw new RuntimeException("创建外置配置文件路径失败，请检查环境");
                    }
                }
                // 移动当前配置文件到外置配置文件中
                String application = "application-" + property.getActive() + ".yml";
                file = new File("./config/" + application);
                if (!file.exists()) {
                    try (OutputStream outputStream = new FileOutputStream(file);
                         InputStream inputStream = property.getResource().getInputStream()) {
                        IOUtils.copy(inputStream, outputStream);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
